package com.qqtech.qquan.mall.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.exception.BizzException;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.dao.BaseDao;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.service.BaseServiceImpl;
import com.qqtech.qquan.mall.cache.MallSysParamCache;
import com.qqtech.qquan.mall.dao.MallProductDao;
import com.qqtech.qquan.mall.dao.MallProductSpecDao;
import com.qqtech.qquan.mall.enums.MallProductStatusDictEnum;
import com.qqtech.qquan.mall.model.MallCategoryVo;
import com.qqtech.qquan.mall.model.MallProduct;
import com.qqtech.qquan.mall.model.MallProductQuery;
import com.qqtech.qquan.mall.model.MallProductSpec;
import com.qqtech.qquan.mall.model.MallProductSpecQuery;
import com.qqtech.qquan.mall.model.MallProductSpecVo;
import com.qqtech.qquan.mall.model.MallProductVo;

@Service
public class MallProductServiceImpl extends BaseServiceImpl<MallProduct>
		implements MallProductService {
	public static final Logger log = LoggerFactory.getLogger(MallProductServiceImpl.class);
	
	@Resource
	private MallProductDao mallProductDao;
	@Resource
	private MallSysParamCache mallSysParamCache;
	@Resource
	private MallProductSpecDao mallProductSpecDao;

	@Override
	protected BaseDao<MallProduct> getBaseDao() {
		return mallProductDao;
	}

	@Override
	public Page<MallProductVo> queryPageListAdmin(MallProduct query,
			Pageable pageable) {
		return mallProductDao.queryPageListAdmin(query, pageable);
	}

	@Override
	public String showRecommendModule(String key) {
		return mallSysParamCache.get(key);
	}

	@Override
	public int handleReduceStock(int productId, int quantity) {
		 return mallProductDao.reduceStock(productId, quantity);
	}

	@Override
	public int handleReturnStock(int productId, int quantity) {
		Preconditions.checkArgument(quantity > 0);
		//商品销量更新
       //handleDecrSaleCount(productId, quantity);
        return mallProductDao.addStock(productId, quantity);
	}

	@Override
	public int handleSaveProduct(MallProduct mallProduct,
			List<MallProductSpecVo> list) {
		if(mallProduct != null && list != null && list.size() > 0){
			int id = mallProductDao.insert(mallProduct);
			for(MallProductSpecVo spec : list){
				spec.setProductId(id);
				spec.setImg(mallProduct.getImg());
				spec.setStatus(YesNoEnum.YES.getCode());
				spec.setNewAt(TimeUtil.now());
				spec.setUpdAt(TimeUtil.now());
				mallProductSpecDao.insert(spec);
			}
			return id;
		}
		
		return 0;
	}

	@Override
	public int handleUpdateProduct(MallProduct mallProduct,
			List<MallProductSpecVo> list) {
		
		if(mallProduct != null && list != null && list.size() > 0){
			for(MallProductSpecVo spec : list){
				if(spec.getId() != null){
					MallProductSpec upodateSpec = mallProductSpecDao.getById(spec.getId());
					if(upodateSpec != null && upodateSpec.getProductId().equals(mallProduct.getId())){
						upodateSpec.setColor(spec.getColor());
						upodateSpec.setSpecName(spec.getSpecName());
						upodateSpec.setStock(spec.getStock());
						upodateSpec.setPrice(spec.getPrice());
						upodateSpec.setMarketPrice(spec.getMarketPrice());
						upodateSpec.setUpdAt(TimeUtil.now());
						upodateSpec.setImg(mallProduct.getImg());
						mallProductSpecDao.updateById(upodateSpec);
					}
				}else{
					MallProductSpec addSpec = new MallProductSpec();
					addSpec.setProductId(mallProduct.getId());
					addSpec.setImg(mallProduct.getImg());
					addSpec.setColor(spec.getColor());
					addSpec.setSpecName(spec.getSpecName());
					addSpec.setStock(spec.getStock());
					addSpec.setPrice(spec.getPrice());
					addSpec.setMarketPrice(spec.getMarketPrice());
					addSpec.setStatus(YesNoEnum.YES.getCode());
					addSpec.setUpdAt(TimeUtil.now());
					addSpec.setNewAt(TimeUtil.now());
					mallProductSpecDao.insert(addSpec);
				}
				
			}
			
			//设置商品价格（最小值）和库存（规格库存总和）
			MallProductSpecQuery query = new MallProductSpecQuery();
			query.setProductId(mallProduct.getId());
			query.setStatus(YesNoEnum.YES.getCode());
			Pageable pageKit = new PageKit(new PageOrder(Direction.DESC, "id"));
			List<MallProductSpecVo> specLst = mallProductSpecDao.queryList(query, pageKit);
			if(specLst != null && specLst.size() > 0){
				Integer totalStock = 0;
				BigDecimal minPrice = BigDecimal.ZERO;
				BigDecimal currentPrice = BigDecimal.ZERO;
				BigDecimal marketPrice = BigDecimal.ZERO;
				BigDecimal currentMarketPrice = BigDecimal.ZERO;
				for(int i=0; i<specLst.size(); i++){
					MallProductSpecVo specVo = specLst.get(i);
					currentPrice = specVo.getPrice();
					currentMarketPrice = specVo.getMarketPrice();
					if(i > 0){
						if(minPrice.compareTo(currentPrice) == 1){//取最小值
							minPrice = currentPrice;
							marketPrice = currentMarketPrice;
						}
					}else{
						minPrice = currentPrice;
						marketPrice = currentMarketPrice;
					}
					totalStock += specVo.getStock(); 
				}
				mallProduct.setPrice(minPrice);
				mallProduct.setMarketPrice(marketPrice);
				mallProduct.setStock(totalStock);
			}
			
			int id = mallProductDao.updateById(mallProduct);
			
 			return id;
		}
		return 0;
	}

	@Override
	public MallProduct getProductBySpecId(Integer specId) {
		return mallProductDao.getProductBySpecId(specId);
	}

	@Override
	public Page<MallProductVo> queryPageBySubject(MallProductQuery subject,
			Pageable pageable) {
		return mallProductDao.queryPageBySubject(subject, pageable);
	}

	@Override
	public int onShelf(int productId) throws BizzException{
		MallProduct productDb = mallProductDao.getById(productId);
		if(productDb== null){
			throw new BizzException("找不到该商品");
		}
		if(productDb.getStatus()==MallProductStatusDictEnum.ONSHELF.getCode()){
			throw new BizzException("该商品已经上架");
		}
		MallProduct product4update = new MallProduct();
		product4update.setId(productId);
		product4update.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
		product4update.setStatusAt(TimeUtil.now());
		return mallProductDao.updateById(product4update);
	}

	@Override
	public int offShelf(int productId) throws BizzException{
		MallProduct productDb = mallProductDao.getById(productId);
		if(productDb== null){
			throw new BizzException("找不到该商品");
		}
		if(productDb.getStatus()==MallProductStatusDictEnum.OFFSHELF.getCode()){
			throw new BizzException("该商品已经下架");
		}
		if(productDb.getStatus()==MallProductStatusDictEnum.DELETE.getCode()){
			throw new BizzException("该商品已经失效");
		}
		MallProduct product4update = new MallProduct();
		product4update.setId(productId);
		product4update.setStatus(MallProductStatusDictEnum.OFFSHELF.getCode());
		product4update.setStatusAt(TimeUtil.now());
		return mallProductDao.updateById(product4update);
	}

	@Override
	public Page<MallProductVo> queryPageByShop(MallProductQuery query,
			Pageable pageable) {
		return mallProductDao.queryPageByShop(query, pageable);
	}

	@Override
	public List<MallCategoryVo> queryShopSellCategory(Integer shopId) {
		List<MallCategoryVo> cateList = new ArrayList<MallCategoryVo>();
		List<MallProductVo> list = mallProductDao.queryShopSellCategory(shopId);
		if (list != null) {
			for (MallProductVo temp : list) {
				if (temp != null && temp.getCategoryId() != null) {
					MallCategoryVo mallCategoryVo = new MallCategoryVo();
					mallCategoryVo.setCategoryId(temp.getCategoryId());
					mallCategoryVo.setName(temp.getCategoryName());
					cateList.add(mallCategoryVo);
				}
			}
		}
		return cateList;
	}

	@Override
	public void increasePv(Integer productId) {
		mallProductDao.increasePv(productId, 1);
	}

	@Override
	public int increaseConcern(Integer productId, int addCount) {
		return mallProductDao.increaseConcern(productId, addCount);
	}

	@Override
	public int getRecommendCount(Integer shopId) {
		if (shopId == null || shopId.intValue() <= 0) {
			return 0;
		}
		MallProductQuery q = new MallProductQuery();
		q.setShopId(shopId);
		q.setIsRecommend(YesNoEnum.YES.getCode());
		q.setStatus(MallProductStatusDictEnum.ONSHELF.getCode());
		return mallProductDao.queryCount(q);
	}
	
}